package de.slothsoft.commons.swing.window.phase;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import de.slothsoft.commons.swing.util.GridBagUtil;

public class PhaseNavigationPanel<I> extends JPanel {

	private static final long serialVersionUID = 1L;

	private final List<Phase<I>> phases;
	private final PhaseChanger<I> changer;
	private int currentIndex;

	public PhaseNavigationPanel(List<Phase<I>> phases, final PhaseChanger<I> changer) {
		this.phases = phases;
		this.changer = changer;
		createComponents();
	}

	protected void createComponents() {
		setOpaque(false);
		createNavigationPhases(this.changer);
	}

	protected void createNavigationPhases(final PhaseChanger<I> changer) {
		setLayout(new GridBagLayout());
		int size = this.phases.size();
		for (int i = 0; i < size; i++) {
			addPhaseNavigation(this.phases.get(i), changer);
		}
	}

	public Component addPhaseNavigation(final Phase<I> phase, final PhaseChanger<I> changer) {
		Component phaseNavigation = createPhaseNavigation(phase, changer);
		addComponent(phaseNavigation);
		return phaseNavigation;
	}

	protected Component createPhaseNavigation(final Phase<I> phase, final PhaseChanger<I> changer) {
		if (phase.isShowInNavigation()) {
			JButton button = new JButton(phase.getTitle());
			button.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					changer.changeToPhase(phase.getId());
				}
			});
			return button;
		}
		return null;
	}

	public void addPlaceholder() {
		addComponent(createPlaceholder());
	}

	protected Component createPlaceholder() {
		JLabel label = new JLabel();
		label.setOpaque(false);
		return label;
	}

	private void addComponent(Component component) {
		if (component == null) {
			return;
		}
		add(component, createGridBagConstraintsForPhase(this.currentIndex++));
	}

	protected GridBagConstraints createGridBagConstraintsForPhase(int index) {
		return GridBagUtil.fillDefaults(0, index);
	}
}